import { useEffect, useState } from 'react';
import { Table, Tag, Card, Select } from 'antd';
import { getTransactions } from '../api/transactions';
import dayjs from 'dayjs';

const Transactions = () => {
  const [transactions, setTransactions] = useState([]);
  const [loading, setLoading] = useState(false);
  const [type, setType] = useState('');
  const [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 0 });

  useEffect(() => {
    fetchTransactions();
  }, [pagination.current, pagination.pageSize, type]);

  const fetchTransactions = async () => {
    setLoading(true);
    try {
      const params = {
        page: pagination.current,
        limit: pagination.pageSize
      };
      if (type) params.type = type;

      const response = await getTransactions(params);
      if (response.success) {
        setTransactions(response.data.transactions);
        setPagination(prev => ({ ...prev, total: response.data.pagination.total }));
      }
    } catch (error) {
      console.error('Fetch transactions error:', error);
    } finally {
      setLoading(false);
    }
  };

  const columns = [
    { title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
    {
      title: '用户',
      dataIndex: ['user', 'name'],
      key: 'userName',
      render: (_, record) => `${record.user.name} (${record.user.phone})`
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (type) => (
        <Tag color={type === 'recharge' ? 'green' : 'orange'}>
          {type === 'recharge' ? '充值' : '消费'}
        </Tag>
      )
    },
    {
      title: '金额',
      dataIndex: 'amount',
      key: 'amount',
      render: (amount) => `¥${parseFloat(amount).toFixed(2)}`
    },
    {
      title: '交易后余额',
      dataIndex: 'balanceAfter',
      key: 'balanceAfter',
      render: (balance) => `¥${parseFloat(balance).toFixed(2)}`
    },
    { title: '备注', dataIndex: 'description', key: 'description' },
    {
      title: '操作员',
      dataIndex: ['operator', 'name'],
      key: 'operator'
    },
    {
      title: '时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (date) => dayjs(date).format('YYYY-MM-DD HH:mm:ss')
    }
  ];

  return (
    <Card
      title="交易记录"
      extra={
        <Select
          style={{ width: 120 }}
          placeholder="交易类型"
          allowClear
          onChange={setType}
          options={[
            { value: 'recharge', label: '充值' },
            { value: 'consume', label: '消费' }
          ]}
        />
      }
    >
      <Table
        columns={columns}
        dataSource={transactions}
        rowKey="id"
        loading={loading}
        pagination={pagination}
        onChange={(newPagination) => setPagination(prev => ({
          ...prev,
          current: newPagination.current,
          pageSize: newPagination.pageSize
        }))}
      />
    </Card>
  );
};

export default Transactions;
